import React, {useEffect} from 'react';
import {Space, Tag} from 'antd';
import LogFactory from 'log/LogFactory';
import {SQL_STATUS_POLL_TIME} from 'config/roll-poling-config';
import RequestHandler from "http/RequestHandler";
import MysqlReplica from "./MysqlReplica";

const log = LogFactory.getLogger("SqlStatus");
export default function SqlStatus() {
    const [ioConnect, setIoConnect] = React.useState<boolean>(false);
    const [sqlConnect, setSqlConnect] = React.useState<boolean>(false);
    // log.debug("SqlStatus ========> render");
    // TODO: 这里需要处理请求失败时候的状态 401 403 500
    useEffect(() => {
        // setTimeout(poll, SQL_STATUS_POLL_TIME);
        poll();
        let iId = setInterval(poll, SQL_STATUS_POLL_TIME);
        return () => {
            log.info("组件卸载,清除定时器");
            clearInterval(iId);
        };
    }, []);
    const poll = async () => {
        if (document.visibilityState === "hidden") {
            log.debug("页面隐藏,不请求sql状态");
            return;
        }
        const res = await RequestHandler.get<MysqlReplica>("/root/status/mysql");
        // log.debug("获取mysql状态", res.data);
        if (res.success) {
            setIoConnect("Yes" === res.data.replicaIORunning);
            setSqlConnect("Yes" === res.data.replicaSQLRunning);
        }
    };
    return (
        <Space size={0}>
            <Tag color={ioConnect ? "#00AA00" : "#AA0000"}>IO</Tag>
            <Tag color={sqlConnect ? "#00AA00" : "#AA0000"}>SQL</Tag>
        </Space>
    );
}
